package com.bibrApp.difu.actvity.login_mvp;


import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bibrApp.difu.Config;
import com.bibrApp.difu.DfApp;
import com.bibrApp.difu.R;
import com.bibrApp.difu.Response.LoginResponseBody;
import com.bibrApp.difu.actvity.main_mvp.MainActivity;
import com.bibrApp.difu.actvity.register_mvp.RegisterActivity;
import com.bibrApp.difu.base.BaseActivity;
import com.bibrApp.difu.dialog.MyCustomDialog;
import com.bibrApp.difu.utils.BiBrShare;
import com.bibrApp.difu.utils.CheckUtils;
import com.bibrApp.difu.utils.IntentUtil;
import com.bibrApp.difu.utils.NetWorkUtil;
import com.bibrApp.difu.utils.ShareUtils;
import com.bibrApp.difu.utils.ToastUtils;
import com.gyf.barlibrary.ImmersionBar;


import androidx.annotation.Nullable;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity<LoginPresenter> implements ILoginView, TextWatcher {

    private ImmersionBar mImmersionBar;
    private Context mContext;

    @BindView(R.id.login_register_tv)
    TextView registerTV;
    @BindView(R.id.login_account_et)
    EditText accountET;
    @BindView(R.id.login_pwd_et)
    EditText pwdET;
    @BindView(R.id.login_pwd_eye_iv)
    ImageView pwdEyeIV;
    @BindView(R.id.login_account_hint_tv)
    TextView accountHintTV;
    @BindView(R.id.login_pwd_hint_tv)
    TextView pwdHintTV;
    @BindView(R.id.login_button)
    Button loginBtn;
    private CountTimer timer;
    private ShareUtils<LoginResponseBody> biBrShare;

    @Override
    protected void initPresenter() {
        presenter = new LoginPresenter(this, this);
        presenter.init();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        mContext = this;
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .fitsSystemWindows(true)
                .init();
        accountET.addTextChangedListener(this);
        pwdET.addTextChangedListener(this);
        biBrShare = BiBrShare.getShare(mContext, Config.FILE_ACCOUNT);
    }


    private String accountStr;
    private String pwdStr;

    //检查登录信息
    private boolean checkLoginInfo() {
        accountStr = accountET.getText().toString();
        pwdStr = pwdET.getText().toString();
        if (!TextUtils.isEmpty(accountStr)) {
            if (CheckUtils.isEmail(accountStr) || CheckUtils.isMobile(accountStr)) {
                accountHintTV.setVisibility(View.INVISIBLE);
                if (!TextUtils.isEmpty(pwdStr) && pwdStr.length() > 5) {
                    pwdHintTV.setVisibility(View.INVISIBLE);
                    return true;
                } else {
                    pwdHintTV.setVisibility(View.VISIBLE);
                    pwdHintTV.setText("密码至少6位");
                }
            } else {
                accountHintTV.setVisibility(View.VISIBLE);
                accountHintTV.setText("账号格式错误");
            }
        } else {
            accountHintTV.setVisibility(View.VISIBLE);
            accountHintTV.setText("账号不能为空");
        }
        return false;
    }


    @Override
    public void error(String msg) {
        ToastUtils.ShowToast(mContext, msg);
    }

    @Override
    public void success(LoginResponseBody data) {
        if (data != null) {
            Log.i("ttt", "---" + data.toString());
            biBrShare.saveData(data, Config.FILE_ACCOUNT_KEY);
            DfApp app = (DfApp) getApplication();

            if (!TextUtils.isEmpty(data.getCenterUserMain().getNickName())) {
                app.setNickName(data.getCenterUserMain().getNickName());
            }
            if (!TextUtils.isEmpty(data.getCenterUserMain().getNickImage())) {
                app.setNickImage(data.getCenterUserMain().getNickImage());
            }
            if (!TextUtils.isEmpty(data.getCenterUserMain().getId())) {
                app.setUserId(data.getCenterUserMain().getId());
            }
            if (!TextUtils.isEmpty(data.getTokenResultBO().getAccess_token())) {
                app.setToken(data.getTokenResultBO().getAccess_token());
            }
            if (!TextUtils.isEmpty(data.getCenterUserMain().getMemberId())) {
                app.setMemberId(data.getCenterUserMain().getMemberId());
            }
            app.setmData(data);
        }
        IntentUtil.toActivity(MainActivity.class, this);
        finish();
    }

    //获取验证码成功
    @Override
    public void successOfCode(String msg) {
        if (timer == null) {
            timer = new CountTimer(60000, 1000);
        }
        timer.start();
        getVerifyCodeTV.setEnabled(false);
        getVerifyCodeTV.setClickable(false);
    }

    private String verifyCodeAccount;

    @Override
    public void successOfLoginCode(int code, String msg, String account) {
        if (code == 501) {
            ToastUtils.ShowToast(mContext, "账户被冻结");
        } else {
            verifyCodeAccount = account;
            changeContentView(code);
        }
    }

    @Override
    public void success(String msg) {
        if (timer == null) {
            timer = new CountTimer(60000, 1000);
        }
        timer.start();
        ToastUtils.ShowToast(mContext, msg);
    }

    /**
     * 500：fail
     * 501：账户被冻结
     * 510：需要谷歌验证码
     * 520：需要手机验证码
     * 530：需要资金安全码
     * 540：需要邮箱验证码
     *
     * @param code 返回状态码
     */
    int mCode = 0;

    private void changeContentView(int code) {
        switch (code) {
            case 510:
                mCode = 510;
                break;
            case 520:
                mCode = 520;
                break;
            case 540:
                mCode = 540;
                break;

            default:
                break;
        }
        showVerifyCodeDialog();
    }

    private MyCustomDialog.Builder mDialog;
    private TextView getVerifyCodeTV;

    /**
     * 获取验证码弹窗
     */
    private void showVerifyCodeDialog() {
        mDialog = new MyCustomDialog.Builder(mContext, R.style.OrderDialogStyle);
        mDialog.setContent(verifyCodeAccount)
                .setTitle(mCode == 520 ? "手机验证" : "邮箱验证")
                .setRightBtnStr("确定")
                .setOnGetVerifyCodeClick(new MyCustomDialog.OnGetVerifyCodeClick() {
                    @Override
                    public void onClickGetVerifyCode(TextView tv) {
                        getCode();
                        getVerifyCodeTV = tv;
                    }
                }).setOnBtnClickListener(new MyCustomDialog.OnButtonClick() {
            @Override
            public void onOk(String checkCode) {
                if (!TextUtils.isEmpty(checkCode) && checkCode.length() >= 4) {
                    mDialog.dismiss();
                    presenter.login(verifyCodeAccount, pwdStr, String.valueOf(mCode), checkCode);
                } else {
                    ToastUtils.ShowToast(mContext, "请输入正确的验证码");
                }
            }

            @Override
            public void onOk() {

            }

            @Override
            public void onCancel() {
                if (timer != null) {
                    timer.cancel();
                    getVerifyCodeTV = null;
                }
            }
        }).show();
    }

    /**
     * 获取验证码
     */
    private void getCode() {
        presenter.getCode(verifyCodeAccount);
    }

    @OnClick(R.id.login_pwd_eye_iv)
    public void eyeIVOnclick() {
        if (pwdET.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
            pwdET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            pwdEyeIV.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.icon_close));
        } else {
            pwdET.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            pwdEyeIV.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.icon_eye));
        }

    }

    @OnClick(R.id.login_button)
    public void loginOnclick() {
        if (!checkLoginInfo()) {
            return;
        }
        /*if (!TextUtils.isEmpty(verifyCodeET.getText().toString().replaceAll(" ", ""))) {
            if (verifyCodeET.getText().toString().length() < 4) {
                verifyCodeHintTV.setText("请输入正确验证码");
            } else {
                LoginBody registerBody = new LoginBody();
                registerBody.setUsername(accountStr);
                registerBody.setPassword(pwdStr);

                Map<String, String> map = EncryptUtils.encrypt(registerBody);

                LoginVerifyCodeBody loginVerifyCodeBody = new LoginVerifyCodeBody();
                loginVerifyCodeBody.setVerifyCode(verifyCodeET.getText().toString().replaceAll(" ", ""));
                loginVerifyCodeBody.setVerifyType(String.valueOf(mCode));

                Map<String, String> map1 = EncryptUtils.encryptVerifyCode(loginVerifyCodeBody);
                map.put("note", map1.get("note"));*/
        if (NetWorkUtil.isNetWorkConnected(mContext)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (NetWorkUtil.isNetworkAvailable(mContext)) {
                    presenter.login(accountStr, pwdStr, "", "");
                } else {
                    ToastUtils.ShowToast(mContext, "网络连接不可用，请您检查网络");
                }
            } else {
                presenter.login(accountStr, pwdStr, "", "");
            }

        } else {
            ToastUtils.ShowToast(mContext, "网络未连接，请您检查网络");
        }

           /* }
        } else {
            verifyCodeHintTV.setText("验证码不能为空");
        }*/
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null) {
            mImmersionBar.destroy();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(accountET.getText().toString().replaceAll(" ", "")) && !TextUtils.isEmpty(pwdET.getText().toString().replaceAll(" ", ""))) {
            loginBtn.setEnabled(true);
            loginBtn.setClickable(true);
        } else {
            loginBtn.setEnabled(false);
            loginBtn.setClickable(false);
        }
    }

    @OnClick(R.id.login_register_tv)
    public void registerOnclick() {
        IntentUtil.toActivity(RegisterActivity.class, mContext);
    }


    class CountTimer extends CountDownTimer {

        public CountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub
            getVerifyCodeTV.setEnabled(true);
            getVerifyCodeTV.setClickable(true);
            getVerifyCodeTV.setText("点击获取");
            getVerifyCodeTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    presenter.getCode(verifyCodeAccount);
                }
            });
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            getVerifyCodeTV.setText((millisUntilFinished / 1000) + "S" + "重新获取");
        }
    }
}
